﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
using ToolUtity;
namespace AHCS
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                //检测当前登录程序是否已经有运行实例
                Process selfInstance = RunningSelfInstance();
                if (selfInstance != null)
                {
                    HandleRunningInstance(selfInstance);
                    Application.Exit();
                }
                else
                {
                    //处理未捕获的异常
                    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                    //处理UI线程异常
                    Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                    //处理非UI线程异常
                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                  
                    ISKeyong();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("应用程序启动错误，" + e.Message);
            }
            
           // Application.Run(new Form1());
        }

        private static void ISKeyong()
        {

         
            string zcb = TimeClass.ReadSetting("saveDay", "");

            if (zcb != "")
            {
                bool isok = false;
                DateTime nettime = Common.GetNetTime(out isok);

                //DateTime nettime = DateTime.Parse("2022-08-24");
                if (isok == false)
                {
                    string mulit = TimeClass.ReadSetting("runMcount", "1");
                    int fenzhong = mulit.ToInt32() ;
                    if (fenzhong>1440)
                    {
                        MessageBox.Show("已经离线使用24小时，请连接网络，否则软件自动退出");
                        Environment.Exit(0);
                    }
                    else
                    {
                        MessageBox.Show("网络连接断开，注意及时保存内容，请在24小时内联网，否则软件自动退出");
                    }
                 
                  
                }
                else
                { 
                    TimeClass.WriteSetting("runMcount", "1");//     清空计时器
                }

                if (Common.ISkeyong())
                {
                    Application.Run(new Form1());
                }
                else
                {
                    Application.Run(new RegForm());
                }
                 
            }
            else
            {
                // 新的用户可用
                string dt = DateTime.Now.AddDays(5).ToString("yyyy-MM-dd");
                string str = Encryption.EncryPW(dt);
                TimeClass.WriteSetting("saveDay", str);
                Common.saveday = 5;
                MessageBox.Show("当前处于免费试用中，请联系公司购买");
                Application.Run(new Form1());
            }
        }
      


        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = "";
            string strDateInfo = "\r\n\r\n出现应用程序未处理的异常：" + DateTime.Now.ToString() + "\r\n";
            Exception error = e.Exception as Exception;
            if (error != null)
            {
                string logInfo = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n", error.GetType().Name, error.Message, error.StackTrace);
                Common.WriteLog(logInfo);
              str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n",
                error.GetType().Name, error.Message);
            }
            else
            {
                str = string.Format("应用程序线程错误:{0}", e);
            }

            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = "";
            Exception error = e.ExceptionObject as Exception;
            string strDateInfo = "出现应用程序未处理的异常：" + DateTime.Now.ToString() + "\r\n";
            if (error != null)
            {
                string logInfo = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r堆栈信息:{1}", error.Message, error.StackTrace);
                Common.WriteLog(logInfo);
                str = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r", error.Message);
            }
            else
            {
                str = string.Format("Application UnhandledError:{0}", e);
            }

            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }



        private static Process RunningSelfInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            //遍历与当前进程名称相同的进程列表
            foreach (Process process in processes)
            {
                //如果实例已经存在则忽略当前进程
                if (process.Id != current.Id)
                {
                    //保证要打开的进程同已经存在的进程来自同一文件路径
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        //返回已经存在的进程
                        return process;
                    }
                }
            }
            return null;
        }

        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(System.IntPtr hWnd);

        private static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, 9); //调用api函数，正常显示窗口
            SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端
        }
    }
}
